#!/usr/bin/env ruby
# Copyright 2017 Google Inc.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

require 'optparse'
require_relative '../../compile/core'
require 'octokit'
require 'time'

# Class to handle Compile include to avoid Rubocop issues.
class CompileClass
  include Compile::Core
end

@options = {
  directory: "#{Dir.pwd}/build/ansible/",
  dry_run: false,
  # Get all PRs from one day ago.
  date: (Time.now - (3600 * 24)).iso8601
}

TEMPLATE = "
<%= ctx[:commit_msg] %>

##### SUMMARY
<%= ctx[:commit_msg] %>
<% if ctx[:prs] && !ctx[:prs].empty?-%>
This PR is the result of the following Magic Modules PRs:
<% ctx[:prs].each do |pr| -%>
  - [<%= pr[:title] -%>](<%= pr[:url] -%>)
<% end -%>
<% end -%>

##### ISSUE TYPE
<% if ctx[:new] -%>
- New Module Pull Request
<% else -%>
- Bugfix Pull Request
<% end -%>

##### ADDITIONAL INFORMATION
```
This was generated by [Magic Modules](https://github.com/googlecloudplatform/magic-modules)
```
".freeze

def all_pr_messages
  # Limit of 50 bug fixes will go into a PR (should never hit this limit)
  client = Octokit::Client.new(access_token: @options[:creds], per_page: 50)
  client.list_issues('googlecloudplatform/magic-modules',
                     labels: 'ansible,downstream-generated',
                     state: 'closed', since: @options[:date].strip)
        .map { |pr| { title: pr[:title], url: pr[:html_url] } }
end

# Get time that user submitted last PR to Ansible.
def time_of_last_pr
  client = Octokit::Client.new(access_token: @options[:creds], per_page: 50)
  last_pr = client.list_issues('ansible/ansible',
                               creator: 'modular-magician',
                               sort: 'created', direction: 'asc').first

  # Return 1 day ago as default if no PRs have been created.
  return (Time.now - (3600 * 24)).iso8601 unless last_pr

  # Timestamp is ISO 8601 by default.
  last_pr[:created_at].iso8601
end

@options = {
  new: false,
  mod_name: '',
  date: time_of_last_pr,
  creds: nil
}

OptionParser.new do |opts|
  opts.banner = 'Usage: run [options]'

  opts.on('--new-module-name [NAME]') do |v|
    @options[:new] = true
    @options[:mod_name] = v
  end

  opts.on('--date [DATE (as ISO8601 String)]',
          'Find all GitHub issues with Ansible label after this date') do |v|
    @options[:date] = v
  end

  opts.on('--github-creds [CREDS]', 'Github creds') do |v|
    @options[:creds] = v
  end
end.parse!

message = if @options[:new]
            "New GCP module: #{@options[:mod_name]}"
          else
            "Bug fixes for GCP (as of #{@options[:date]})"
          end

puts CompileClass.new.lines(
  CompileClass.new.compile_string({
                                    commit_msg: message,
                                    new: @options[:new],
                                    prs: all_pr_messages
                                  }, TEMPLATE)
)
